(function() {
  "use strict";
  APP.Views.MainView = Backbone.View.extend({
    events : {
      // "contextmenu #menuBase .item": "appContextMenu",
      "click .com-management": "comManagementShow"
    },
    initialize: function(params) {
      APP.mainView = this;
      this.tiles = {};
      this.nogroup = params.nogroup;
      // var callback = {
      //   obj: this,
      //   name: 'getMenuDataSuccess'
      // }
      // APP.BeClient.getMenuData(callback, undefined, {
      //   preloaderShow: false,
      //   preloaderHide: false
      // });
    },
    getMenuDataSuccess: function(data) {
      var applications = [
        {
          name: 'Position manager',
          tiles: [
            {
              "id":1,
              "name":"Moje stanowiska",
              "description":"<strong>Position manager</strong> - lista stanowisk",
              "ico":"fa fa-users",
              "icoType":1,
              "url":"http://pm.vw-group.pl/",
              "userPulpit":null,
              "data":[
                {
                  "label":"Do zaakceptowania",
                  "description":"",
                  "type":"int",
                  "value":"3",
                  "important":true
                }
              ],
              "links":null
            },
            {
              "id":2,
              "name":"Moi podwładni",
              "description":"<strong>Position manager</strong> - list moich podwładnych",
              "ico":"fa fa-users",
              "icoType":1,
              "url":"http://pm.vw-group.pl/",
              "userPulpit":null,
              "data":[
                {
                  "label":"Liczba podwładnych",
                  "description":"",
                  "type":"int",
                  "value":"8",
                  "important":false
                }
              ],
              "links":null
            },
          ]
        },
        {
          name: 'Ocena pracownicza',
          tiles: [
            {
              "id":3,
              "name":"Moje cele premiowe",
              "description":"<strong>Ocena pracownicza</strong> - formularz zawierający opis moich celi premiowych",
              "ico":"fa fa-gift",
              "icoType":1,
              "url":"http://pm.vw-group.pl/",
              "userPulpit":null,
              "data":[
                {
                  "label":"Liczba dni pozostała do wypełnienia celów",
                  "description":"",
                  "type":"int",
                  "value":"5",
                  "important":true
                },
                {
                  "label":"Liczba dni pozostała do rozliczenia celów",
                  "description":"",
                  "type":"int",
                  "value":"65",
                  "important":false
                }
              ],
              "links":null
            },
            {
              "id":4,
              "name":"Lista celi premiowych podwładnych",
              "description":"<strong>Ocena pracownicza</strong> - lista zawierająca wszystkie formularze z celami premiowymi podwładnych",
              "ico":"fa fa-gift",
              "icoType":1,
              "url":"http://pm.vw-group.pl/",
              "userPulpit":null,
              "data":[
                {
                  "label":"Do zaakceptowania",
                  "description":"",
                  "type":"int",
                  "value":"2",
                  "important":false
                },
                {
                  "label":"Do uzupełnienia",
                  "description":"",
                  "type":"int",
                  "value":"6",
                  "important":false
                }
              ],
              "links":null
            },
            {
              "id":5,
              "name":"Raporty oceny pracowniczej",
              "description":"<strong>Ocena pracownicza</strong> - raporty",
              "ico":"fa fa-gift",
              "icoType":1,
              "url":"http://pm.vw-group.pl/",
              "userPulpit":null,
              "data":null,
              "links":null
            },
          ]
        },
        {
          name: 'RCP',
          tiles: [
            {
              "id":6,
              "name":"Kalendarz czasu pracy",
              "description":"<strong>RCP</strong> - kalendarz",
              "ico":"glyphicon glyphicon-dashboard",
              "icoType":1,
              "url":"http://pm.vw-group.pl/",
              "userPulpit":null,
              "data":[
                {
                  "label":"Liczba dni do korekty",
                  "description":"",
                  "type":"int",
                  "value":"15",
                  "important":true
                }
              ],
              "links":null
            },
            {
              "id":7,
              "name":"Zleć pracę w nadgodzinach",
              "description":"<strong>RCP</strong> - zleć pracę w nadgodzinach",
              "ico":"glyphicon glyphicon-dashboard",
              "icoType":1,
              "url":"http://pm.vw-group.pl/",
              "userPulpit":null,
              "data":null,
              "links":null
            },
            {
              "id":8,
              "name":"Raporty czasu pracy",
              "description":"<strong>RCP</strong> - raporty",
              "ico":"glyphicon glyphicon-dashboard",
              "icoType":1,
              "url":"http://pm.vw-group.pl/",
              "userPulpit":null,
              "data":null,
              "links":null
            }
          ] 
        },
        {
          name: 'Szkody',
          tiles: [
            {
              "id":9,
              "name":"Zarejestrowane szkody",
              "description":"<strong>Szkody</strong> - zarejestrowane szkody",
              "ico":"fa fa-truck",
              "icoType":1,
              "url":"http://pm.vw-group.pl/",
              "userPulpit":null,
              "data":[
                {
                  "label":"Ilość szkód",
                  "description":"",
                  "type":"int",
                  "value":"7",
                  "important":false
                }
              ],
              "links":null
            },
            {
              "id":10,
              "name":"Zarejestruj szkodę",
              "description":"<strong>Szkody</strong> - zarejestruj szkodę",
              "ico":"fa fa-truck",
              "icoType":1,
              "url":"http://pm.vw-group.pl/",
              "userPulpit":null,
              "data":null,
              "links":null
            },
            {
              "id":11,
              "name":"Raporty szkód",
              "description":"<strong>Szkody</strong> - raporty szkód",
              "ico":"fa fa-truck",
              "icoType":1,
              "url":"http://pm.vw-group.pl/",
              "userPulpit":null,
              "data":null,
              "links":null
            }
          ]
        },
        {
          name: 'Helpdesk',
          tiles: [
            {
              "id":12,
              "name":"Zgłoś projekt",
              "description":"<strong>Helpdesk</strong> - zgłoś projekt",
              "ico":"fa fa-ambulance",
              "icoType":1,
              "url":"http://pm.vw-group.pl/",
              "userPulpit":null,
              "data":[
                {
                  "label":"Twoje projekty",
                  "description":"",
                  "type":"int",
                  "value":"5",
                  "important":false
                }
              ],
              "links":null
            },
            {
              "id":13,
              "name":"Zgłoś awarię",
              "description":"<strong>Helpdesk</strong> - zgłoś awarię",
              "ico":"fa fa-ambulance",
              "icoType":1,
              "url":"http://pm.vw-group.pl/",
              "userPulpit":null,
              "data":[
                {
                  "label":"Twoje awarie",
                  "description":"",
                  "type":"int",
                  "value":"0",
                  "important":false
                }
              ],
              "links":null
            },
            {
              "id":14,
              "name":"Włącz usługi",
              "description":"<strong>Helpdesk</strong> - włącz usługi",
              "ico":"fa fa-ambulance",
              "icoType":1,
              "url":"http://pm.vw-group.pl/",
              "userPulpit":null,
              "data":[
                {
                  "label":"Twoje usługi",
                  "description":"",
                  "type":"int",
                  "value":"6",
                  "important":false
                }
              ],
              "links":null
            },
            {
              "id":14,
              "name":"Lista zgłoszeń",
              "description":"<strong>Helpdesk</strong> - liczba zgłoszeń",
              "ico":"fa fa-ambulance",
              "icoType":1,
              "url":"http://pm.vw-group.pl/",
              "userPulpit":null,
              "data":[
                {
                  "label":"Twoje zgłoszenia",
                  "description":"",
                  "type":"int",
                  "value":"3",
                  "important":false
                }
              ],
              "links":null
            }
          ]
        },
        {
          name: 'eFaktury',
          tiles:[
            {
              "id":15,
              "name":"Moje faktury",
              "description":"<strong>eFaktury</strong> - moje faktury",
              "ico":"glyphicon glyphicon-list-alt",
              "icoType":1,
              "url":"http://pm.vw-group.pl/",
              "userPulpit":null,
              "data":[
                {
                  "label":"Liczba faktur",
                  "description":"",
                  "type":"int",
                  "value":"19",
                  "important":false
                }
              ],
              "links":null
            },
            {
              "id":16,
              "name":"Dodaj klienta",
              "description":"<strong>eFaktury</strong> - dodaj klienta",
              "ico":"glyphicon glyphicon-list-alt",
              "icoType":1,
              "url":"http://pm.vw-group.pl/",
              "userPulpit":null,
              "data":[
                {
                  "label":"Liczba klientów",
                  "description":"",
                  "type":"int",
                  "value":"26",
                  "important":false
                }
              ],
              "links":null
            },
            {
              "id":17,
              "name":"Raporty eFaktur",
              "description":"<strong>eFaktury</strong> - raporty",
              "ico":"glyphicon glyphicon-list-alt",
              "icoType":1,
              "url":"http://pm.vw-group.pl/",
              "userPulpit":null,
              "data":null,
              "links":null
            }
          ]
        }
      ];
      var self = this;
      this.$el.html(_.template($('#mainTemplate').html(), {}));
      this.$('#menuBase').hide(0);
      var view = null;
      _.each(applications, function(group) {
        if (!self.nogroup)
          self.$('#menuBase').append('<h4 class="">'+group.name+'</h4>');
        _.each(group.tiles, function(application) {
          view = new APP.Views.TileView({
            application: application
          });
          self.$('#menuBase').append(view.render().el);
          self.tiles[application.id] = view;
        });
      });
      this.$('#menuBase .item').hide(0);
      this.$('#menuBase').show(0);
      this.showTiles();
      this.attacheDragEndDropMenu();
    },
    saveUserPulpitVisibilitiesSuccess: function(data) {
      var callback = {
        obj: this,
        name: 'getMenuDataUpdateSuccess'
      }
      APP.BeClient.getMenuData(callback, undefined, {hiddenApplicationIds: data.hiddenApplicationIds});
    },
    getMenuDataUpdateSuccess: function(data, options) {
      var self = this;
      _.each(options.hiddenApplicationIds, function(id) {
        if (self.tiles[id] != undefined) {
          self.tiles[id].remove();
          self.tiles[id] = undefined;
        }
      });
      var view = null;
      _.each(data.applications, function(application) {
        if (self.tiles[application.id] == undefined) {
          view = new APP.Views.TileView({
            application: application
          });
          self.$('#menuBase').append(view.render().el);
          self.tiles[application.id] = view;
        }
      });
      this.$('#menuBase').masonry('reload');
      this.saveOrder();
    },
    saveOrder: function() {
      // var order = [];
      // _.each(this.$('#menuBase .item'), function(item) {
      //   order.push(parseInt($(item).attr('data-id')));
      // });
      // APP.BeClient.saveOrder(order, undefined, undefined, {
      //   preloaderShow: false,
      //   preloaderHide: false
      // });
    },
    showTiles: function() {
      var self = this;
      $('#menuBase .item:not(:visible):first').fadeIn(200);
      if ($('#menuBase .item:not(:visible)').length > 0) {
        setTimeout(function(){
          self.showTiles();
        }, 40);
      }
    },
    appMouseUp: function(e) {
      e.preventDefault();
      // if (e.target.tagName == 'A')
      //   return;
      // if (e.which == 1) {
      //   var $e = $(e.currentTarget);
      //   if (!$e.hasClass('dragging'))
      //     window.open($e.attr('data-url'), "_blank");
      // }
    },
    appContextMenu: function(e) {
      e.preventDefault();
      var appId = parseInt($(e.currentTarget).attr('data-id'));
      var menuView = new APP.Views.AppMenuView({
        appId: appId,
        appView: this.tiles[appId],
        menuView: this,
        coord: {
          x: e.pageX,
          y: e.pageY
        }
      });
      $('html').append(menuView.render().el);
      var removeMenu = function() {
        menuView.remove();
        $('body').off('mouseup');
      }
      $('body').on('mouseup', removeMenu);
    },
    attacheDragEndDropMenu: function() {
      var t = this.$('#menuBase');
      var self = this;
      t.masonry({
        itemSelector: '.layout-card, h4',
        isResizable: true,
        columnWidth: 100,
        isAnimated: true
      });
      t.sortable({
        items: '.layout-card',
        axis: "xy",
        forcePlaceholderSize: true,
        placeholder: 'card-sortable-placeholder layout-card',
        tolerance: 'pointer',
        opacity: 0.95,
        revert:300,
        start: function(event, ui) {
          self.$('.item').off('mouseup');
          ui.item.addClass('dragging').removeClass('layout-card');
          if ( ui.item.hasClass('long') ) {
            ui.placeholder.addClass('long');
          }
          if ( ui.item.hasClass('vlong') ) {
            ui.placeholder.addClass('vlong');
          }
          ui.item.parent().masonry('reload')
        },
        change: function(event, ui) {
          APP.offset = ui.placeholder.offset();
          ui.item.parent().masonry('reload');
        },
        stop: function(event, ui) {
          ui.item.removeClass('dragging').addClass('layout-card');
          self.$('.item').on('mouseup', self.appMouseUp);
          ui.item.parent().masonry('reload');
          self.saveOrder();
        }
      });
      this.$('.item').on('mouseup', this.appMouseUp);
    },
    renderLoader: function() {
      this.$el.html(_.template($('#mainLoaderTemplate').html(), {}));
      return this;
    }
  });
}());